#!/usr/bin/python3
# -*-coding:utf-8 -*-
import socket
import cv2
import numpy
import time

sock = socket.socket()
host = socket.gethostname()
port = 12345
sock.connect((host,port))

# 接受图片大小的信息
def recv_size(sock, count):
    buf = ''
    while count:
        newbuf = sock.recv(count).decode()
        if not newbuf: return None
        buf += newbuf
        count -= len(newbuf)
    return buf

flag = 0

while True:
        flag = ~flag
        time.sleep(2)
        if flag:
                print("request a frame")
                sock.send(b'##')
                length = recv_size(sock, 16)  # 首先接收来自客户端发送的大小信息
                if len(length) == 16:  # 若成功接收到大小信息，进一步再接收整张图片
                        print("receive the frame")
                        stringData = sock.recv(int(length))
                        data = numpy.fromstring(stringData, dtype='uint8')
                        decimg = cv2.imdecode(data, 1)  # 解码处理，返回mat图片
                        cv2.imshow('SERVER', decimg)
                        cv2.waitKey(0)
                        if cv2.waitKey(100)  & 0xff == ord("q"):
                                cv.destroyAllWindows()